package com.tzinfo.tzb;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tzinfo.data.PostResult;
import com.tzinfo.data.PostResultData;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.view.adapter.PostAdapter;
import com.tzinfo.tzb.view.adapter.PostAdapter2;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage_NoData;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/22.
 */


public class PostActivity2 extends Activity implements PostAdapter2.PostInterface {
    private int fid;
    private int tid;
    private PullToRefreshListView listView;
    int pagesize = 10;
    private boolean isLoadingData = false;
    int page=1;
    private int Invisible=0;//应该还需要加入三个按钮，未审核，已删除，正常(加入点击事件改变该参数值)
    List<PostResultData> listData;
    private PostAdapter2 adapter;
    private int i;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post2);
        Intent intent = getIntent();
        tid = intent.getExtras().getInt("tid");


        listView = (PullToRefreshListView) findViewById(R.id.post_listView);
//        listView.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout endLabels = listView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉加载更多");
        endLabels.setReleaseLabel("松开加载");
        endLabels.setRefreshingLabel("正在加载");
        new GetDataTask().execute();
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        PostActivity2.this,
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);


                if (!isLoadingData) {
                    page = 1;
                    refreshView.getLoadingLayoutProxy()
                            .setLastUpdatedLabel(label);
                    new GetDataTask().execute();
                }
            }
        });
//        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//            @Override
//            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//                String label = DateUtils.formatDateTime(
//                        PostActivity.this,
//                        System.currentTimeMillis(),
//                        DateUtils.FORMAT_SHOW_TIME
//                                | DateUtils.FORMAT_SHOW_DATE
//                                | DateUtils.FORMAT_ABBREV_ALL);
//
//
//                if (!isLoadingData) {
//                    page = 1;
//                    refreshView.getLoadingLayoutProxy()
//                            .setLastUpdatedLabel(label);
//                    new GetDataTask().execute();
//                }
//
//            }
//
//            @Override
//            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                String label = DateUtils.formatDateTime(
//                        PostActivity.this,
//                        System.currentTimeMillis(),
//                        DateUtils.FORMAT_SHOW_TIME
//                                | DateUtils.FORMAT_SHOW_DATE
//                                | DateUtils.FORMAT_ABBREV_ALL);
//                // 显示最后更新的时间
//                if (!isLoadingData) {
//                    refreshView.getLoadingLayoutProxy()
//                            .setLastUpdatedLabel(label);
//                    new GetDataTask().execute();
//                }
//            }
//        });





    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void screen(int Uid) {
        ScreenTask screenTask = new ScreenTask();
        screenTask.execute(String.valueOf(Uid));
    }

    @Override
    public void delete(int a, int b, String s, int position) {
        OperationTask operationTask = new OperationTask();
        i=position;
        operationTask.execute(String.valueOf(a),String.valueOf(b),s);
    }

    public class OperationTask extends AsyncTask<String, Void, ResultMessage_NoData> {

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("pid", params[1]));

            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/Forumpostdel.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            try{
                ResultMessage_NoData result = gson.fromJson(DataString, ResultMessage_NoData.class);
                return result;
            }
            catch (Exception e){
            }
            return null;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData resultMessage_noData) {
            super.onPostExecute(resultMessage_noData);
            if (resultMessage_noData==null){
                Toast.makeText(PostActivity2.this,"数据请求失败",Toast.LENGTH_SHORT).show();
            }
            else if (resultMessage_noData.getSuccess()){
                Toast.makeText(PostActivity2.this,resultMessage_noData.getErrorMsg(),Toast.LENGTH_SHORT).show();
                listData.remove(i);
                adapter.notifyDataSetChanged();
            }
        }
    }

    public class GetDataTask extends AsyncTask<String, Void, PostResult> {
        protected void onPreExecute() {
            super.onPreExecute();
            if (isLoadingData) {
                this.cancel(true);
                return;
            }
            isLoadingData = true;

        }

        @Override
        protected PostResult doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            pairs.add(new BasicNameValuePair("Invisible", String.valueOf(Invisible)));//默认 -2：未审核；-5已删除;0:正常
            if (getIntent().getExtras().getInt("fid")!=0)
            pairs.add(new BasicNameValuePair("fid", String.valueOf(fid)));
            pairs.add(new BasicNameValuePair("tid", String.valueOf(tid)));
            pairs.add(new BasicNameValuePair("type", "0"));//0为管理员
            pairs.add(new BasicNameValuePair("page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumpostListM.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            PostResult result = gson.fromJson(DataString, PostResult.class);
            return result;
        }

        @Override
        protected void onPostExecute(PostResult result) {
            super.onPostExecute(result);
            if (result.getData().size()>0) {
                if (adapter == null || page == 1) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                }
                if (listData.size() <= pagesize) {
                    adapter = new PostAdapter2(PostActivity2.this, listData);
                    listView.setAdapter(adapter);

                }

                page++;
                adapter.notifyDataSetChanged();
                listView.onRefreshComplete();
                isLoadingData = false;

            } else {
                Toast.makeText(PostActivity2.this, "没有数据", Toast.LENGTH_SHORT)
                        .show();
                listView.onRefreshComplete();
                isLoadingData = false;
            }
        }
    }

    public class ScreenTask extends AsyncTask<String,Void,ResultMessage_NoData>{

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            pairs.add(new BasicNameValuePair("type", "Screen"));
            pairs.add(new BasicNameValuePair("Ouid", params[0]));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/UserOp.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            ResultMessage_NoData result = gson.fromJson(DataString, ResultMessage_NoData.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData resultMessage_noData) {
            super.onPostExecute(resultMessage_noData);
            if (resultMessage_noData.getSuccess()){
                Toast.makeText(PostActivity2.this,resultMessage_noData.getErrorMsg(),Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode==RESULT_OK)
            page=1;
            new GetDataTask().execute();
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void goback(View view) {
        this.finish();
    }
}
